import { Injectable } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';
import { readdirSync, readFileSync } from 'fs';

@Injectable()
export class FileService {
  private readonly filesPath = path.join(__dirname, '..', 'files');

  writeFile(data: string, fileName: string): void {
    const filePath = path.join(this.filesPath, fileName);
    fs.writeFileSync(filePath, data, { encoding: 'utf8' });
  }

  readFile(fileName: string): string {
    const filePath = path.join(this.filesPath, fileName);
    if (!fs.existsSync(filePath)) {
      return 'File not found';
    }
    return fs.readFileSync(filePath, { encoding: 'utf8' });
  }

  getAllData(): any[] {
    const files = readdirSync(this.filesPath);
    let combinedData: string[] = [];

    files.forEach((file) => {
      if (file.endsWith('.json')) {
        const filePath = path.join(this.filesPath, file);
        const fileContent = readFileSync(filePath, 'utf-8');
        const dataArray = JSON.parse(fileContent);
        combinedData = combinedData.concat(dataArray);
      }
    });

    return combinedData;
  }

  getAllUsers(): any[] {
    const files = readdirSync(this.filesPath);
    return files
      .filter((file) => file.endsWith('.json')) // Возвращаем только JSON файлы
      .map((file) => path.parse(file).name);
  }
}
